package com.leetcode.Offer;

import java.util.ArrayList;

public class JZ58_I_2 {
    public String reverseWords(String s) {
        if (s == null || s.length() == 0) {
            return "";
        }
        String tmp = s.trim().replaceAll("\\s+", " ");
        ArrayList<String> list = new ArrayList<>();
        StringBuilder builder = new StringBuilder();
        for (char c : tmp.toCharArray()) {
            if (c != ' ') {
                builder.append(c);
            } else {
                list.add(builder.toString());
                builder = new StringBuilder();
            }
        }
        list.add(builder.toString());
        builder = new StringBuilder();
        for (int i = list.size() - 1; i >= 0; i--) {
            builder.append(list.get(i)).append(" ");
        }
        return builder.toString().trim();

    }
}
